package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.OrganizationCode;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.system.OrgUtils;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.domain.utills.DateUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import java.util.*;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Path("OrganzizationCodeService")
@Slf4j
public class OrganzizationCodeService extends ApplicationBaseService {
    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);

    @Path("getInviteCodes")
    @POST
    @Operation(summary = "供应商邀请码-添加邀请码", tags = CUSTOM_SERVICE)
    public SingleResponse<BO> getInviteCodes(@Parameter OrganizationCode organizationCode) {
        log.info("--------------------获取邀请码-------------------", JSONObject.toJSONString(organizationCode));
        if (StringUtils.isBlank(organizationCode.getInviteCodes())) {
            return SingleResponse.buildFailure("-1", "参数不合法");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("code", organizationCode.getInviteCodes());
        String sql ="select * from "+getTableName(ModelConst.T_ORGANIZATION_INVITE_CODE)+" where code = :code " +
                "AND expire >= NOW() AND (vendor_organization_id is null or vendor_organization_id = '') ";
        List<Map<String, Object>> boList = JdbcTemplateUtils.queryForList(sql, param);
        if (!CollectionUtils.isEmpty(boList)&&boList.size()==1) {
            Map<String, Object> dataMap = new HashMap<>();
            Map<String, Object> resultMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(boList)) {
                dataMap = boList.get(0);
            }
            Date expire = (Date) dataMap.get("expire");
            if (expire.getTime() < DateUtils.getCurrentDate().getTime()) {
                return SingleResponse.buildFailure("-1", "邀请码已过期");
            }
            SelectorFormat  vendorOrganization = OrgUtils.getOrgByUserId().createSelectorFormat();
            Map<String, Object> count = JdbcTemplateUtils.builder(ModelConst.T_ORGANIZATION_INVITE_CODE).selectField("count(*) as num")
                    .eq("vendor_organization_id ->'$.id'", vendorOrganization.getId())
                    .eq("customer_organization_id ->'$.id'", JsonParseObject.parseObject((String) dataMap.get("customer_organization_id"), SelectorFormat.class).get(0).getId())
                    .queryForMap();
            if ((Long) count.get("num") >= 1) {
                return SingleResponse.buildFailure("-1", "不可重复邀请");
            }
            // 设置拥有者为供应商
            resultMap.put("owner", RequestContext.getCorpLoginId());
            resultMap.put("vendor_organization_id", vendorOrganization);
            resultMap.put("vendor_organization_name", vendorOrganization.getName());
            resultMap.put("id", dataMap.get("id"));
            List<Map<String, Object>> paramList = new ArrayList<>();
            paramList.add(resultMap);
            return BoServiceUtils.updateMainBo(ModelConst.T_ORGANIZATION_INVITE_CODE, paramList);
        } else {
            return SingleResponse.buildFailure("-1", "邀请码无效！");
        }
    }
}
